﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SDF.Web.Framework
{
    public class RemoteCall
    {
        public string HttpGet(string StrUrl, int Timeout = 60)
        {
            string strResult = string.Empty;

            HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(StrUrl);
            myReq.Timeout = Timeout * 1000;
            myReq.ServicePoint.ConnectionLimit = 50;
            myReq.KeepAlive = false;
            System.Net.ServicePointManager.DefaultConnectionLimit = 50;

            HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
            Stream myStream = HttpWResp.GetResponseStream();
            StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
            StringBuilder strBuilder = new StringBuilder();
            while (-1 != sr.Peek())
            {
                strBuilder.Append(sr.ReadLine());
            }

            myReq.Abort();
            HttpWResp.Close();
            sr.Close();

            strResult = strBuilder.ToString();

            return strResult;
        }

        public string HttpPost(string url, IDictionary<string, string> parameters, int timeout = 60)
        {
            HttpWebRequest request = null;

            var charset = Encoding.UTF8;
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = timeout * 1000;

            //如果需要POST数据     
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = charset.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            var response = request.GetResponse() as HttpWebResponse;

            Stream myStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(myStream, charset);
            StringBuilder strBuilder = new StringBuilder();
            while (-1 != sr.Peek())
            {
                strBuilder.Append(sr.ReadLine());
            }
            response.Close();
            sr.Close();

            return strBuilder.ToString();
        }
    }
}
